import '../public/index'
import url from '../data/url'
import request from '../data/request'
import {header} from '../data/config'
import store from 'store'

import {price as valid_price} from '../data/validate'

const base = url.base,
  addOBuildingType = request.addOrModifyBuildingType,
  getDeveloperList = request.getDeveloperList,
  getBuildingList = request.getBuildingList,
  getChannelAll = request.getChannelAll,
  getPaychannelList = request.getPaychannelList,
  getBuildingTypeList = request.getBuildingtypeList

// 页面标题
const title = '楼盘户型',
  action = '修改'

let form = new Vue({
  el: '#form',
  data: () => ({
    name: '',
    developerId: '',
    developerList: [],
    buildingId: '',
    propertyList: [],
    buildingType: '',
    buildingTypeList: [],
    payChannelList: [],
    payChannel: '',
    upgradeChannel: '',
    isPos: 0,
    flagUpgrade: 0,
    isShow: 1,
    price: '',
    equalMoney: '',
    isLock: true
  }),
  mounted: function () {

    let that = this;

    let loading = layer.msg('初始化数据中...', {
      icon: 16,
      time: 0
    })

    Promise
      .all([this.getDeveloper(), this.getBuildingList(), this.getBuildingTypeList(), this.getPayChannel()])
      .then((res) => {

        layer.close(loading)

        that.developerList = res[0].object;
        that.propertyList = res[1].object;
        that.buildingTypeList = res[2].object;
        that.payChannelList = res[3].object;

        let storeData = store.get('storeData');
        console.log('old storeData===>>', storeData)

        //在这里处理storeData里边的equalMoney字段和price字段
        function showNum(num) {
          let numStr = (num / 100).toFixed(2)
          // console.log(numStr)
          const pointIndex = numStr.indexOf('.')

          let lastNum = numStr[pointIndex + 1] + numStr[pointIndex + 2]
          // console.log('lastNum===>', lastNum)
          if (lastNum == 0) { //没有角没有分
            return (num / 100).toFixed(0)
          } else if (lastNum[1] == 0 && lastNum[0] > 0) { //有角没有分  100.01
            return (num / 100).toFixed(1)
          } else { //有角有分或者 没有角有分
            return numStr
          }
        }

        storeData.equalMoney = showNum(storeData.equalMoney)
        storeData.price = showNum(storeData.price)

        console.log('new storeData====>>>', storeData)

        if (!storeData) {
          layer.msg('页面跳转错误', {
            icon: 5
          })

          setTimeout(() => {
            window.location = './index.html'
          }, 1000)

          return
        }

        that.isLock = false

        $.extend(that.$data, storeData, {
          buildingType: storeData.type,
          developerId: storeData.developerName
        })

        valid()

        setTimeout(() => {
          that.initSelect();
        }, 0)
      })
      .catch((error) => {
        console.log(error)

        layer.close(loading)
        layer.msg(error || '初始化数据失败', {
          icon: 5
        })
      })

  },
  methods: {
    // 获取开发商列表
    getDeveloper: () => (
      new Promise((resolve, reject) => {

        $.ajax({
          url: base + getDeveloperList,
          headers: header
        })
          .done(function (res) {
            if (res.code === 0) {
              resolve(res)
            }
            reject(res.message)
          })
          .fail(function () {
            console.log("error")
            reject()
          })
          .always(function () {
          })

      })

    ),
    // 获取大额渠道
    getPayChannel: () => (
      new Promise((resolve, reject) => {

        $.ajax({
          url: base + getChannelAll,
          headers: header
        })
          .done(function (res) {
            if (res.code === 0) {
              resolve(res)
            }
            reject(res.message)
          })
          .fail(function () {
            console.log("error")
            reject()
          })
          .always(function () {
          })

      })

    ),
    // 获取楼盘列表
    getBuildingList: () => (
      new Promise((resolve, reject) => {

        $.ajax({
          url: base + getBuildingList,
          headers: header
        })
          .done(function (res) {
            if (res.code === 0) {
              resolve(res)
            }
            reject(res.message)
          })
          .fail(function () {
            console.log("error")
            reject()
          })
          .always(function () {
          })

      })

    ),
    // 获取楼盘类型列表
    getBuildingTypeList: () => (
      new Promise((resolve, reject) => {

        $.ajax({
          url: base + getBuildingTypeList,
          headers: header
        })
          .done(function (res) {
            if (res.code === 0) {
              resolve(res)
            }
            reject(res.message)
          })
          .fail(function () {
            console.log("error")
            reject()
          })
          .always(function () {
          })

      })

    ),
    //初始化快捷下拉选择框
    initSelect: function () {
      let that = this;

      $(this.$refs.select)
        .selectize({
          create: true,
          onChange: function (val) {
            that.developerId = val
          }
        })
    }
  }
})

function valid() {

  let form_valid,
    $form = $('#form')

  $.validator.setDefaults({ // 只能放在validate规则配置之前

    // 提交事件
    submitHandler: () => {
      console.log('submit!')

      let loading_modal = layer.msg('提交中...', {
        icon: 16,
        time: 0
      })

      form.isLock = true

      const form_price = new Number(form.$data.price)
      const form_equalMoney = new Number(form.$data.equalMoney)
      $.ajax({
        url: base + addOBuildingType,
        type: 'POST',
        headers: header,
        contentType: 'application/json',
        data: JSON.stringify({
          id: form.$data.idStr,
          buildingId: form.$data.buildingId,
          type: form.$data.buildingType,
          price: form_price.toFixed(2) * 100,
          equalMoney: form_equalMoney.toFixed(2) * 100,
          upgradeChannel: form.$data.upgradeChannel,
          flagUpgrade: form.$data.flagUpgrade,
          isShow: form.$data.isShow,
          isPos: form.$data.isPos,
          payChannel: form.$data.payChannel
        })
      })
        .done(function (res) {
          console.log(res)

          if (res.code === -1) {
            layer.msg(res.message, {
              icon: 5
            })

            form.isLock = false;

            return
          }

          layer.msg(`${ action }${ title }成功`, {
            icon: 6
          })

          // 重置表单
          $.extend(form.$data, form.$options.data());

          setTimeout(() => {
            window.location = './index.html'
          }, 1000)
        })
        .fail(function (res) {
          console.log(res)

          layer.msg(`${ action }${ title }失败`, {
            icon: 5
          })

          console.log("error");
        })
        .always(function (res) {

          layer.close(loading_modal);
          form.isLock = false

        })

    }
  })

  // 验证
  form_valid = $form.validate({
    errorPlacement: function (error, element) {
      element.parents('.col-sm-12').length ? error.appendTo(element.parents('.col-sm-12')) : error.appendTo(element.parents('.col-xs-24'))
    },
    rules: {
      name: {
        required: true
      },
      developerId: {
        required: true
      },
      buildingId: {
        required: true
      },
      buildingType: {
        required: true
      },
      price: valid_price,
      equalMoney: valid_price
    }
  })

}